$(document).ready(function() {
	construirMapa();	
	agregarCampo();
});

//Input
//var iconURL = "http://ejemploquickdb.googlecode.com/svn/trunk/PruebaDB/icons/marker";
var iconURL = "https://calendar.google.com/googlecalendar/images/favicon_v2010_";
var nextinput = 0;

function agregarCampo(){
	nextinput++;
	campo = '<li id="rut'+nextinput+'">Dirección:<input class="campoUltimo" type="text" size="20" id="campo' + nextinput + '"  name="campo' + nextinput + '"  /><img src="'+ iconURL + nextinput + '.ico"/></li>';
	$("#campos").append(campo);
	var code=null, ultimoCampo = $("#campo" + nextinput);
	ultimoCampo.keypress(function(e) {
	code= (e.keyCode ? e.keyCode : e.which);
	if (code == 13){
		ultimoCampo.unbind("keypress");
		codeAddress($(this).val() + ", CABA, Buenos Aires, Argentina");
		e.preventDefault();
		agregarCampo();
		}
	});
	ultimoCampo.focus();
}

//Google Map's
var map;
var geocoder;

function construirMapa() {
    geocoder = new google.maps.Geocoder();
    var myLatlng = new google.maps.LatLng(-34.578385,-58.434372);
    var myOptions = {
      zoom: 12,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapa"), myOptions);
}

function codeAddress(address) {
    if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
	if (status == google.maps.GeocoderStatus.OK) {
	for(var i=0; i<results.length; i++) {
		var marker = new google.maps.Marker({
		      map: map, 
		      position: results[i].geometry.location,
		      icon: iconURL + (nextinput - 1) + ".ico"
		  });
	}
    } else {
	alert("Geocode was not successful for the following reason: " + status);
    }
});
    }
  }